package cn.bgs.serviceedu.service.impl;

import cn.bgs.serviceedu.entity.Customer;
import cn.bgs.serviceedu.dao.CustomerMapper;
import cn.bgs.serviceedu.service.CustomerService;
import cn.bgs.serviceutils.utils.CSException;
import cn.bgs.serviceutils.utils.JwtUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import cn.hutool.crypto.digest.MD5;

/**
 * <p>
 * 客户表 服务实现类
 * </p>
 *
 * @author YiChen
 * @since 2021-10-20
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    private JavaMailSender mailSender;

    //邮件发件人
    @Value("${spring.mail.username}")
    private String from;

    @Override
    public String login(Customer customer) {
        Customer one = lambdaQuery().eq(Customer::getCustomerCode,customer.getCustomerCode()).one();

        if (one == null){
            throw new CSException(20001,"账号不存在");
        }
        MD5 md5 = new MD5();
        String s = md5.digestHex(customer.getPassWord());
        if (!s.equals(one.getPassWord())){
            throw new CSException(20001,"密码错误");
        }
        return JwtUtils.getJwtToken(one.getCustomerId(),one.getCustomerName());

    }



    /**
     * 邮箱验证码
     * @param messages
     * @param email
     */
    @Override
    public void sendMail(String messages, String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("农务医生APP消息");//标题
        message.setText(messages);//主题内容
        message.setFrom(from);//发件邮箱
        message.setTo(email);//收件邮箱
        try {
            mailSender.send(message);//发送
        } catch (MailException e) {
            throw new CSException(20001,"邮件发送失败");
        }
    }
}
